package com.gcloud.mesh.distributedSchedule;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.gcloud.framework.db.PageResult;
import com.gcloud.mesh.asset.enums.DeviceType;
import com.gcloud.mesh.asset.service.IAssetService;
import com.gcloud.mesh.distributedSchedule.cluster.CommonCluster;
import com.gcloud.mesh.distributedSchedule.scheduler.Scheduler;
import com.gcloud.mesh.framework.core.SpringUtil;
import com.gcloud.mesh.header.enums.MonitorMeter;
import com.gcloud.mesh.header.msg.asset.ListDeviceMsg;
import com.gcloud.mesh.header.vo.asset.DatacenterItemVo;
import com.gcloud.mesh.header.vo.asset.DeviceItemVo;
import com.gcloud.mesh.monitor.service.StatisticsCheatService;
import com.gcloud.mesh.monitor.service.StatisticsService;
import com.gcloud.mesh.sdk.GceSDK;
import com.gcloud.mesh.sdk.gce.ClusterVo;
import com.gcloud.mesh.supplier.dao.SupplierDao;
import com.gcloud.mesh.supplier.enums.K8sClusterType;
import com.gcloud.mesh.supplier.enums.SystemType;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class UpdateClusterResourceTask {

	// @Autowired
	// private GceSDK gceSdk;

	@Autowired
	private SupplierDao supplierDao;

	@Autowired
	private StatisticsService statisticsService;

	@Autowired
	private StatisticsCheatService statisticsCheatService;

	@Autowired
	IAssetService assetService;

	public static Scheduler schduler = new Scheduler(0);

	@Scheduled(fixedDelay = 1000 * 60)
	public void work() {
		log.info("[UpdateClusterResourceTask] 更新集群资源定时器开始");

		GceSDK sdk = SpringUtil.getBean(GceSDK.class);

		PageResult<DatacenterItemVo> res = assetService.pageDatacenter(1, 999, null, null, null);
		for (DatacenterItemVo item : res.getList()) {

			CommonCluster cluster = new CommonCluster(item.getId(), 0);

			 initCluster(sdk, cluster);
//			initCheatCluster(cluster);

			try {
				schduler.updateCluster(cluster);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		log.info("[UpdateClusterResourceTask] 更新集群资源定时器结束");
	}

	private void initCheatCluster(CommonCluster cluster) {

		int cpuCores = 0;
		double memSpaceG = 0;
		int storageSpaceG = 0;
		int bandWidthKBPS = 0;

		double kwhCost = 10;
		int maxInputPowerKwh = 0;
		int serverPowerWatt = 0;
		int refrigerationPowerWatt = 0;
		int psuLossPowerWatt = 0;
		int devicePowerWatt = 0;

		int restCpuCores = 0;
		double restMemSpaceG = 0;
		int restStorageSpaceG = 0;
		int restBandWidthKBPS = 0;

		int cpuCoreNum = 0;
		float highestCpuFrequencyG = 0;
		int L2CacheSizeKB = 0;
		int cpuTDP = 140;
		double memorySizeG = 0;
		float memorySpeedG = 0;

		ListDeviceMsg msg = new ListDeviceMsg();
		msg.setDatacenterId(cluster.getId());
		msg.setType(DeviceType.SERVER.getNo());
		List<DeviceItemVo> devices = assetService.listDevice(msg);

		// 以下数据获取集群单个节点
		if (devices.size() > 0) {
			String cpuCoresStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_CPU_CORES.getMeter(),
					devices.get(0).getId());
			String memorySizeStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_MEM_TOTAL.getMeter(),
					devices.get(0).getId());
			String memorySpeedStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_MEM_SPEED.getMeter(),
					devices.get(0).getId());
			String cpuL2CacheStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_CPU_l2CACHE.getMeter(),
					devices.get(0).getId());
			String cpuFrequencyStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_CPU_FREQUENCY.getMeter(),
					devices.get(0).getId());
			String storageSpaceGStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_STORAGE_TOTAL.getMeter(),
					devices.get(0).getId());
			String restStorageSpaceGStr = statisticsCheatService
					.latestSample(MonitorMeter.SERVER_STORAGE_AVAILABLE.getMeter(), devices.get(0).getId());
			String bindwidthStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_BANDWIDTH.getMeter(),
					devices.get(0).getId());
			String serverPowerStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_POWER.getMeter(),
					devices.get(0).getId());
			
			String memSpaceGStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_MEM_TOTAL.getMeter(),
					devices.get(0).getId());

			if (!cpuCoresStr.isEmpty()) {
				cpuCores = (int) Double.parseDouble(cpuCoresStr);
				restCpuCores = cpuCores / 2;
			}
			if (!memSpaceGStr.isEmpty()) {
				memSpaceG = (int) Double.parseDouble(memSpaceGStr);
				restMemSpaceG = memSpaceG / 2;
			}
			if (!cpuCoresStr.isEmpty()) {
				cpuCoreNum = (int) Double.parseDouble(cpuCoresStr);
			}
			if (!memorySizeStr.isEmpty()) {
				memorySizeG = (int) Double.parseDouble(memorySizeStr);
			}
			if (!memorySpeedStr.isEmpty()) {
				memorySpeedG = (float) Double.parseDouble(memorySpeedStr);
			}
			if (!cpuL2CacheStr.isEmpty()) {
				L2CacheSizeKB = (int) Double.parseDouble(cpuL2CacheStr);
			}
			if (!cpuFrequencyStr.isEmpty()) {
				highestCpuFrequencyG = (float) Double.parseDouble(cpuFrequencyStr);
			}
			if (!storageSpaceGStr.isEmpty()) {
				storageSpaceG = (int) Double.parseDouble(storageSpaceGStr) / 1024;
			}
			if (!restStorageSpaceGStr.isEmpty()) {
				restStorageSpaceG = (int) (Double.parseDouble(restStorageSpaceGStr) / 1024);
			}
			if (!bindwidthStr.isEmpty()) {
				restBandWidthKBPS = bandWidthKBPS = (int) Double.parseDouble(bindwidthStr);
			}
			if (!serverPowerStr.isEmpty()) {
				maxInputPowerKwh = (int) Double.parseDouble(serverPowerStr) / 1000;
			}
		}

		cluster.init(cpuCores, memSpaceG, storageSpaceG, bandWidthKBPS, kwhCost, maxInputPowerKwh);
		if (serverPowerWatt > 0 && refrigerationPowerWatt > 0 && psuLossPowerWatt > 0 && devicePowerWatt > 0) {
			cluster.updateInstantPower(serverPowerWatt, refrigerationPowerWatt, psuLossPowerWatt, devicePowerWatt);
		} else {
			// 直接采用PUE
			String pueId = supplierDao.getConfigValueByDatacenterIdAndConfigName(cluster.getId(),
					SystemType.SS.getName(), K8sClusterType.HOST_IP.getName());
			if (pueId != null) {
				String pueStr = statisticsCheatService.latestSample(MonitorMeter.PUE.getMeter(), pueId);
				cluster.updatePue(Double.parseDouble(pueStr));
			} else {
				log.warn("未获取到集群PUE数据。 集群ID：" + cluster.getId());
			}
		}

		cluster.updateInstantRestResource(restCpuCores, restMemSpaceG, restStorageSpaceG, restBandWidthKBPS);
		cluster.setupPerformanceInfo(cpuCoreNum, highestCpuFrequencyG, L2CacheSizeKB, cpuTDP, memorySizeG,
				memorySpeedG);
	}

	private void initCluster(GceSDK sdk, CommonCluster cluster) {

		int cpuCores = 0;
		double memSpaceG = 0.0;
		int storageSpaceG = 0;
		int bandWidthKBPS = 0;
		// 暂时预设单位电价为10，单位未定
		double kwhCost = 10;
		int maxInputPowerKwh = 0;

		int restCpuCores = 0;
		double restMemSpaceG = 0.0;
		int restStorageSpaceG = 0;
		int restBandWidthKBPS = 0;

		int serverPowerWatt = 0;
		int refrigerationPowerWatt = 0;
		int psuLossPowerWatt = 0;
		int devicePowerWatt = 0;

		int cpuCoreNum = 0;
		float highestCpuFrequencyG = 0;
		int L2CacheSizeKB = 0;
		// 暂时预设TDP数值为140w
		int cpuTDP = 140;
		int memorySizeG = 0;
		float memorySpeedG = 0;

		String clusterId = supplierDao.getConfigValueByDatacenterIdAndConfigName(cluster.getId(),
				SystemType.K8S.getName(), K8sClusterType.CLUSTER_ID.getName());

		// 获取k8s集群资源数据
		ClusterVo vo = null;
		if (clusterId != null) {
			vo = sdk.detailCluster(clusterId);
		}

		if (vo != null && vo.getCluster() !=null) {
			String voCpuCores = vo.getCluster().getCapacity().get("cpu");
			String voRestCpuCores = vo.getCluster().getRequested().get("cpu");

			String voMemSpaceG = vo.getCluster().getCapacity().get("memory");
			String voRestMemSpaceG = vo.getCluster().getRequested().get("memory");

			if (voCpuCores.endsWith("m") || voRestCpuCores.endsWith("m")) {
				voCpuCores = voCpuCores.replace("m", "");
				voRestCpuCores = voRestCpuCores.replace("m", "");
			}
			cpuCores = Integer.valueOf(voCpuCores);
			restCpuCores = Integer.valueOf(voRestCpuCores) / 1024;

			if (voMemSpaceG.endsWith("i") || voRestMemSpaceG.endsWith("i")) {
				if (voMemSpaceG.endsWith("Ki")) {
					memSpaceG = Double.valueOf(voMemSpaceG.replace("Ki", "")) / 1024 / 1024;
				} else if (voMemSpaceG.endsWith("Mi")) {
					memSpaceG = Double.valueOf(voMemSpaceG.replace("Mi", "")) / 1024;
				} else if (voMemSpaceG.endsWith("Gi")) {
					memSpaceG = Double.valueOf(voMemSpaceG.replace("Gi", ""));
				} else {
					memSpaceG = 0.0;
				}

				if (voRestMemSpaceG.endsWith("Ki")) {
					restMemSpaceG = Double.valueOf(voRestMemSpaceG.replace("Ki", "")) / 1024 / 1024;
				} else if (voRestMemSpaceG.endsWith("Mi")) {
					restMemSpaceG = Double.valueOf(voRestMemSpaceG.replace("Mi", "")) / 1024;
				} else if (voRestMemSpaceG.endsWith("Gi")) {
					restMemSpaceG = Double.valueOf(voRestMemSpaceG.replace("Gi", ""));
				} else {
					restMemSpaceG = 0.0;
				}
			} else {
				memSpaceG = Double.valueOf(voMemSpaceG);
				restMemSpaceG = Double.valueOf(voRestMemSpaceG);
			}
		}

		ListDeviceMsg msg = new ListDeviceMsg();
		msg.setDatacenterId(cluster.getId());
		msg.setType(DeviceType.SERVER.getNo());
		List<DeviceItemVo> devices = assetService.listDevice(msg);

		// 以下数据获取集群单个节点
		if (devices.size() > 0) {
			String cpuCoresStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_CPU_CORES.getMeter(),
					devices.get(0).getId());
			String memorySizeStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_MEM_TOTAL.getMeter(),
					devices.get(0).getId());
			String memorySpeedStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_MEM_SPEED.getMeter(),
					devices.get(0).getId());
			String cpuL2CacheStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_CPU_l2CACHE.getMeter(),
					devices.get(0).getId());
			String cpuFrequencyStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_CPU_FREQUENCY.getMeter(),
					devices.get(0).getId());
			String storageSpaceGStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_STORAGE_TOTAL.getMeter(),
					devices.get(0).getId());
			String restStorageSpaceGStr = statisticsCheatService
					.latestSample(MonitorMeter.SERVER_STORAGE_AVAILABLE.getMeter(), devices.get(0).getId());
			String bindwidthStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_BANDWIDTH.getMeter(),
					devices.get(0).getId());
			String serverPowerStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_POWER.getMeter(),
					devices.get(0).getId());

			if (!cpuCoresStr.isEmpty()) {
				cpuCoreNum = (int) Double.parseDouble(cpuCoresStr);
			}
			if (!memorySizeStr.isEmpty()) {
				memorySizeG = (int) Double.parseDouble(memorySizeStr);
			}
			if (!memorySpeedStr.isEmpty()) {
				memorySpeedG = (float) Double.parseDouble(memorySpeedStr);
			}
			if (!cpuL2CacheStr.isEmpty()) {
				L2CacheSizeKB = (int) Double.parseDouble(cpuL2CacheStr);
			}
			if (!cpuFrequencyStr.isEmpty()) {
				highestCpuFrequencyG = (float) Double.parseDouble(cpuFrequencyStr);
			}
			if (!storageSpaceGStr.isEmpty()) {
				storageSpaceG = (int) Double.parseDouble(storageSpaceGStr) / 1024;
			}
			if (!restStorageSpaceGStr.isEmpty()) {
				restStorageSpaceG = (int) (Double.parseDouble(restStorageSpaceGStr) / 1024);
			}
			if (!bindwidthStr.isEmpty()) {
				restBandWidthKBPS = bandWidthKBPS = (int) Double.parseDouble(bindwidthStr);
			}
			if (!serverPowerStr.isEmpty()) {
				maxInputPowerKwh = (int) Double.parseDouble(serverPowerStr) / 1000;
			}

		}

		cluster.init(cpuCores, memSpaceG, storageSpaceG, bandWidthKBPS, kwhCost, maxInputPowerKwh);
		if (serverPowerWatt > 0 && refrigerationPowerWatt > 0 && psuLossPowerWatt > 0 && devicePowerWatt > 0) {
			cluster.updateInstantPower(serverPowerWatt, refrigerationPowerWatt, psuLossPowerWatt, devicePowerWatt);
		} else {
			// 直接采用PUE
			String pueId = supplierDao.getConfigValueByDatacenterIdAndConfigName(cluster.getId(),
					SystemType.SS.getName(), K8sClusterType.HOST_IP.getName());
			if (pueId != null) {
				String pueStr = statisticsCheatService.latestSample(MonitorMeter.PUE.getMeter(), pueId);
				cluster.updatePue(Double.parseDouble(pueStr));
			} else {
				log.warn("未获取到集群PUE数据。 集群ID：" + cluster.getId());
			}
		}
		cluster.updateInstantRestResource(restCpuCores, restMemSpaceG, restStorageSpaceG, restBandWidthKBPS);
		cluster.setupPerformanceInfo(cpuCoreNum, highestCpuFrequencyG, L2CacheSizeKB, cpuTDP, memorySizeG,
				memorySpeedG);
	}
}
